﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;

namespace Seagull.ZHD1X
{
    // TODO: disposable
    internal class SmsSender
    {
        protected SerialPort Port = null;
        protected SerialDataReceivedEventHandler DataReceivedEventHandler = null;

        public SmsSender()
        {
            DataReceivedEventHandler = Port_DataReceived;
        }

        public void Open(string name, int rate)
        {
            if(Port != null && Port.IsOpen)
            {
                Port.Close();
                Port = null;
            }

            if(Port == null)
            {
                Port = new SerialPort(name, rate);
                Port.DataReceived += DataReceivedEventHandler;
            }

            Port.Open();
        }

        public bool Send(string telnum, string text)
        {
            Port.DataReceived -= DataReceivedEventHandler;

            byte[] utext = Encoding.BigEndianUnicode.GetBytes(text);

            byte[] prefix = Encoding.ASCII.GetBytes("SMSU" + telnum + "," + utext.Length.ToString("00") + ":");

            byte[] buf = new byte[prefix.Length + utext.Length];

            prefix.CopyTo(buf, 0);

            utext.CopyTo(buf, prefix.Length);

            try
            {
                Port.Write(buf, 0, buf.Length);

                return (Port.ReadLine().StartsWith("SMSS OK"));
            }
            finally
            {
                Port.DataReceived += DataReceivedEventHandler;
            }
        }

        void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if(e.EventType == SerialData.Eof || e.EventType == SerialData.Chars)
            {
                Console.Write(Port.ReadExisting());
            }
        }

        public void Close()
        {
            if(Port != null && Port.IsOpen)
            {
                Port.Close();
            }

            Port = null;
        }
    }
}
